package com.gxa.employment.exception;

import com.gxa.employment.common.Result;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 全局异常处理器
 * @Author:
 * @DateTime: 2025/3/5 21:06
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public Result handleException(Throwable e) {
        e.printStackTrace();
        //业务异常
        if (e instanceof BizException) {
            return Result.error(((BizException) e).getCode(), e.getMessage());
         //参数校验异常
        }else if(e instanceof MethodArgumentNotValidException){
            StringBuilder builder = new StringBuilder();
            ((MethodArgumentNotValidException)e).getBindingResult()
                    .getFieldErrors()
                    .forEach(fieldError -> builder
                            .append(fieldError.getField())
                            .append(" : ")
                            .append(fieldError.getDefaultMessage())
                            .append("  "));
            return Result.error(500, builder.toString());
        }
        //系统异常
        return Result.error();
    }
}
